<template>
  <div class="detail">
    <h1>{{ product.data?.name }}</h1>
    <p style="color: orangered">
      价格：<strong>￥</strong>{{ product.data?.price }}
    </p>
    <div class="content" v-html="product.data?.content"></div>
    <action-bar>
      <action-bar-icon icon="home-o" text="首页" @click="toHome" />
      <action-bar-icon icon="search" text="搜索" @click="toList" />
      <action-bar-icon
        icon="cart-o"
        text="购物车"
        @click="toCart"
        :badge="cartCount"
      />
      <action-bar-button
        type="warning"
        text="加入购物车"
        @click="addCart(product.data)"
      />
      <action-bar-button
        type="danger"
        text="立即购买"
        @click="toBuy(product.data.id)"
      />
    </action-bar>
  </div>
</template>

<script setup>
import { reactive, inject } from "vue"; //reactive用来定义响应式数据，官方建议基本数据类型使用ref，复杂数据类型使用reactive
import { useRoute, useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { ActionBar, ActionBarIcon, ActionBarButton, Toast, Badge } from "vant";
import { loadProductByIdAPI } from "../server/products";
import { isLogined } from "../utils/auth";
// import { addToCratAPI } from "../server/shop-carts";
import { useCart } from "../store/carts-num";

const { push } = useRouter();
const { query } = useRoute();
const product = reactive({});

// 全局 pinia 下的购物车数量
const store = useCart();
const { cartCount } = storeToRefs(store);

// const cartCount = inject("cartCount");
// 根据商品ID加载商品信息
loadProductByIdAPI(query.id).then((res) => {
  // console.log(res);
  product.data = res.data;
  // console.log(product.data);
});

const toHome = () => {
  push({
    name: "home",
  });
};

const toCart = () => {
  push({
    name: "cart",
  });
};

const toList = () => {
  push({
    name: "list",
  });
};
// 加入购物车
const addCart = async (item) => {
  if (isLogined()) {
    // await addToCratAPI({
    //   product: item.id,
    //   price: item.price,
    //   amount: 1,
    // });
    store.addCart(item.id, 1, item.price);
    Toast({
      message: "加入购物车成功",
    });
    // 点击加入购物车的时候需要设置购物车数量
    // cartCount.value++;
  } else {
    Toast({
      message: "请先登录",
    });
    setTimeout(() => {
      push({
        name: "login",
      });
    }, 1000);
  }
};
// 立即购买（待完善）
const toBuy = (id) => {
  // Toast.success("购买成功");
  // 跳转到订单页
  if (isLogined()) {
    push({
      name: "order",
      query: {
        id,
      },
    });
  } else {
    Toast({
      message: "请先登录",
    });
    setTimeout(() => {
      push({
        name: "login",
      });
    }, 1000);
  }
};
</script>
